<template>
  <div ref="echartRef" class="echart"></div>
</template>
<script setup lang="ts">
import { type PropType, onMounted, onUnmounted, shallowRef, unref, watch, nextTick } from 'vue'
import type { EChartsOption } from 'echarts'
import * as echarts from 'echarts'
const props = defineProps({
  options: {
    type: Object as PropType<EChartsOption>
  }
})

const echartRef = shallowRef<HTMLDivElement>()
const chartInstance = shallowRef<echarts.ECharts | null>()

const resizeObserver = new ResizeObserver(resize)
onMounted(async () => {
  await nextTick()
  resizeObserver.observe(echartRef.value)

  chartInstance.value = echarts.init(echartRef.value, 'light')

  watch(
    () => props.options,
    (val) => {
      if (val) {
        chartInstance.value?.setOption(unref(val), { notMerge: true })
      }
    },
    {
      immediate: true,
      deep: true
    }
  )
})

function resize () {
  chartInstance.value?.resize({
    animation: {
      duration: 300,
      easing: 'quadraticIn'
    }
  })
}

onUnmounted(() => {
  resizeObserver.disconnect()
})

defineExpose({
  chartInstance
})
</script>
<style lang="scss" scoped>
.echart {
  height: 100%;
  width: 100%;
}
</style>
